<template>
  <div :id="id">
    <Portal to="right-disable"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card shadow="never"
               :style="{height: gadgetHeight + 'px',border:0}"
               class="aui-card--fill">
        <div>
          <div class="cardHeader"
               @mouseenter="mouseenter(true)"
               @mouseleave="mouseenter(false)"
               v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
            <span>
              <span class="cardTitle threepoints"
                    :title="widgetName"
                    v-if='widgetName && widgetName.trim().length>0'>{{ widgetName}}</span>
              <el-tooltip :open-delay="1000" class="item"
                          effect="dark"
                          :content="gadgetSetting.headerDescription"
                          placement="right"
                          v-if='gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0'>
                <i class="cuifont icon_help_circle cardIcon"></i>
              </el-tooltip>
            </span>
            <MoreMenu :slicer='slicer'
                      :gadgetId='id'
                      :gadgetType='gadgetInfo.com'
                      @updateQuery="query"
                      @fullScreen="fullScreen" />
          </div>
          <div class="control-section">
            <div class="content-wrapper">
              <ejs-chart v-if="isHasData"
                         ref="barchart"
                         :theme='theme'
                         :style="{height: gadgetHeight-45 + 'px'}"
                         align='center'
                         :width='chartWidth'
                         :title='gadgetSetting.title'
                         :primaryXAxis='gadgetSetting.primaryXAxis'
                         :primaryYAxis='gadgetSetting.primaryYAxis'
                         :chartArea='gadgetSetting.chartArea'
                         :tooltip='gadgetSetting.tooltip'
                         :zoomSettings='gadgetSetting.zoomSettings'
                         :load='load'
                         :pointClick="onClick">
                <e-series-collection v-if="gadgetSetting.valueFieldsNameManyY?gadgetSetting.valueFieldsNameManyY.length>0:false">
                  <e-series v-for="(item,index) in dataSource"
                            style="padding:5px 0px"
                            :key="index"
                            :dataSource="item.data"
                            :type="gadgetSetting.type"
                            :xName="gadgetSetting.valueFieldsNameMeasureX"
                            :yName="item.name"
                            :name="item.name"
                            :marker="gadgetSetting.marker"></e-series>
                </e-series-collection>
                <e-series-collection v-else>
                  <e-series v-for="(item,index) in dataSource"
                            style="padding:5px 0px"
                            :key="index"
                            :dataSource="item.data"
                            :type="gadgetSetting.type"
                            :xName="gadgetSetting.valueFieldsNameMeasureX"
                            :yName="gadgetSetting.valueFieldsNameMeasureY"
                            :name="item.name"
                            :marker="gadgetSetting.marker"></e-series>
                </e-series-collection>
              </ejs-chart>
              <div v-else
                   class="gadget-no-data">
                <el-image @click="query()"
                          :src='noDataImageUrl'
                          fit='fill'></el-image>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <Lastupdatetime v-if="currentTime"
                      :currentTime="currentTime"></Lastupdatetime>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <div style="position:absolute;left:9999px;">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType='notgridgadget' />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'

import { JSONGroupbyName, JsonGroupList } from '@/utils/common'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'

export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      currentTime: null,
      theme: 'Material',
      dataSource: [{ name: 'a', data: [{ x: 0, y: 0 }] }],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      dataSource1: null,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'barchartgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'barchartgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: ''
    }
  },

  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    this.query()
    this.subscribeMessage('runReport', this.query)
    this.$store.state.isWidget = false
  },
  mounted () {

  },
  methods: {
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 45
      this.gadgetWidth = newWPx
      this.chartWidth = (newWPx - 10) + 'px'
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    upgradeGadgetSetting (setting) {

    },
    onClick (e) {
      // var pointx = ''
      var isTrim = false
      // e.point.x: "2"
      // e.point.y: "2"
      // e.series.xName:'status'
      // e.series.yName:'id'
      // e.series.properties.name: "Data Analyst"

      // if (!e.point) {
      //   e.point = {}
      //   pointx = e.series.dataSource[e.seriesIndex][e.series.xName]
      // } else {
      //   pointx = e.point.x
      // }
      // if (pointx === 'Null') {
      //   pointx = ' is null'
      // } else if (pointx === ' ') {
      //   isTrim = true
      //   pointx = "= ''"
      // } else {
      //   pointx = "= '" + pointx + "'"
      // }
      var tempAlias = ''
      var tempData = ''
      var alias = ''
      var pointx = ''
      if (!e.point) {
        e.point = {}
        pointx = e.series.dataSource[e.pointIndex][e.series.xName]
      } else {
        pointx = e.point.x
      }
      if (pointx === 'Null') {
        pointx = ' is null'
      } else if (pointx === ' ') {
        isTrim = true
        pointx = "''"
      }
      if (this.queryDrillthroughList && this.queryDrillthroughList.length > 0) {
        for (let index = 0; index < this.queryDrillthroughList.length; index++) {
          const element = this.queryDrillthroughList[index]
          if (e.series.dataSource[e.pointIndex][element.alias]) {
            if (isTrim) {
              tempData = 'trim("' + (element.field || '') + '")' + "'" + (e.series.dataSource[e.pointIndex][element.alias] ? e.series.dataSource[e.pointIndex][element.alias] : '') + "'"
            } else {
              tempData = '"' + (element.field || '') + '"' + "='" + (e.series.dataSource[e.pointIndex][element.alias] ? e.series.dataSource[e.pointIndex][element.alias] : '') + "'"
            }
          } else {
            var list = this.selectFields.filter(item => item.queryId === (this.selectFields.find(item => item.alias === e.series.yName).queryId))
            var fieldObj = list.find(i => i.dataType === 'dimension')
            if (!fieldObj) {
              continue
            } else {
              var field = fieldObj.field
              if (isTrim) {
                tempData = 'trim("' + (field || '') + '")' + "'" + pointx + "'"
              } else {
                tempData = '"' + (field || '') + '"' + '' + "='" + pointx + "'"
              }
              break
            }
          }
        }
      } else {
        if (this.queryDrillthrough && this.queryDrillthrough.alias) {
          tempAlias = e.series.dataSource[e.pointIndex][this.queryDrillthrough.alias]
          if (!tempAlias) {
            alias = 'dimension1'
          } else {
            alias = this.queryDrillthrough.alias
          }
          pointx = e.series.dataSource[e.pointIndex][alias]
          if (isTrim) {
            tempData = 'trim("' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : this.queryDrillthrough.columnName) + '")' + "'" + pointx + "'"
          } else {
            tempData = '"' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : this.queryDrillthrough.columnName) + '"' + "='" + pointx + "'"
          }
        }
      }
      this.queryId = this.selectFields.find(item => item.alias === e.series.yName) ? this.selectFields.find(item => item.alias === e.series.yName).queryId : ''
      if (this.queryId) {
        let data = ''
        data = tempData
        this.findOriginData(data)
      }
    },
    query () {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.loading = true
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        this.currentTime = new Date()
        _self.verifyHasData(res)
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
          _self.upgradeGadgetSetting(_self.gadgetSetting)
        }
        if (res.name) {
          _self.widgetName = res.name
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        _self.selectFields = res.selectFields
        let objList = []
        for (let i = 0; i < res.selectFields.length; i++) {
          const element = res.selectFields[i]
          if (element.dataType === 'dimension') {
            objList.push(element)
          }
        }
        if (Array.isArray(objList) && objList.length > 1) {
          _self.queryDrillthroughList = objList
        } else {
          _self.queryDrillthrough = objList[0] || {}
          _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
        }
        this.setComponentList(res.selectFields)
        this.$nextTick(() => {
          var temp = []
          if (_self.gadgetSetting.valueFieldsNameManyY && _self.gadgetSetting.valueFieldsNameManyY.length > 0) {
            temp = JsonGroupList(_self.chartLabelFormat(res.data, res.selectFields), _self.gadgetSetting.valueFieldsNameManyY)
          } else {
            temp = JSONGroupbyName(_self.chartLabelFormat(res.data, res.selectFields), _self.gadgetSetting.valueFieldsNameMeasureGroup)
          }
          temp.forEach(item => {
            item.data.forEach(i => {
              for (var key in i) {
                if (typeof i[key] === 'boolean') {
                  i[key] = i[key].toString()
                }
              }
            })
          })
          _self.dataSource = temp
        })
        _self.$forceUpdate()
        _self.$set(_self.gadgetSetting.primaryXAxis, 'title', _self.gadgetSetting.xName ? _self.gadgetSetting.xName : _self.gadgetSetting.valueFieldsNameMeasureX)
        _self.$set(_self.gadgetSetting.primaryYAxis, 'title', _self.gadgetSetting.yName ? _self.gadgetSetting.yName : _self.gadgetSetting.valueFieldsNameMeasureY)
        _self.$set(_self.gadgetSetting.primaryXAxis, 'labelIntersectAction', 'Rotate45')
        _self.loading = false
      }).catch(() => {
        _self.loading = false
      })
    },
    load (args) {
      args.chart.series[0].marker.dataLabel.font.color = '#000000'
    },
    chartLabelFormat (data, fieldsList) {
      let temp = data.map(item => {
        for (const key in item) {
          let fieldItemIndex = fieldsList.findIndex(e => e['alias'] === key)
          fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
          fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
          if (fieldItemIndex === -1) {
            continue
          }
          let fieldType = fieldsList[fieldItemIndex]['businessType']
          if (this.gadgetSetting.valueFieldsNameMeasureY !== key && (fieldType === 'date' || fieldType === 'datetime')) {
            let templateName = this.getFormatTemplateName(fieldsList, key)
            item[key] = this.getFormatData(item[key], templateName) || item[key]
          }
        }
        return item
      })
      return temp
    },
    getFormatData (value, templateName) {
      try {
        return this.$refs[templateName][0].format(value)
      } catch (error) {
        return value
      }
    },
    setComponentList (fieldsList) {
      let temp = []
      fieldsList.map(e => {
        let name = this.findTemplateName(e['fieldsFormat'], e['businessType'])
        name && temp.push(name)
      })
      this.formatComponentList = this._.uniq(temp)
    }
  }
})
</script>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
